<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

/**
 * 症状分类管理控制器
 */
class SymptomCategory extends Base
{
    /**
     * 获取症状分类列表
     */
    public function index()
    {
        $page = input('page', 1);
        $limit = input('limit', 20);
        $keyword = input('keyword', '');

        $where = [];
        if (!empty($keyword)) {
            $where[] = [
                'name_zh_cn|name_en_us|name_ja_jp|name_be_by',
                'like',
                '%' . $keyword . '%'
            ];
        }

        $list = Db::name('symptom_categories')
            ->where($where)
            ->order('sort_order asc, id asc')
            ->paginate($limit, false, ['page' => $page]);

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 获取单个症状分类
     */
    public function read()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        $category = Db::name('symptom_categories')->find($id);

        if (!$category) {
            return json(['code' => 1, 'msg' => '数据不存在']);
        }

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $category
        ]);
    }

    /**
     * 创建症状分类
     */
    public function save()
    {
        $data = input('post.');

        // 验证必填字段
        $required = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($data[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }


        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('symptom_categories')->insert($data);

        if ($result) {
            return json(['code' => 0, 'msg' => '创建成功']);
        } else {
            return json(['code' => 1, 'msg' => '创建失败']);
        }
    }

    /**
     * 更新症状分类
     */
    public function update()
    {
        $id = input('id');
        $data = input('post.');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 验证必填字段
        $required = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($data[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }


        $data['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('symptom_categories')->where('id', $id)->update($data);

        if ($result !== false) {
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 删除症状分类
     */
    public function delete()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 检查是否有关联的症状
        $symptomCount = Db::name('symptoms')->where('category_id', $id)->count();
        if ($symptomCount > 0) {
            return json(['code' => 1, 'msg' => '该分类下还有症状，无法删除']);
        }

        $result = Db::name('symptom_categories')->delete($id);

        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
    }

    /**
     * 批量删除
     */
    public function deleteMultiple()
    {
        $ids = input('ids');

        if (empty($ids) || !is_array($ids)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 检查是否有关联的症状
        $symptomCount = Db::name('symptoms')->whereIn('category_id', $ids)->count();
        if ($symptomCount > 0) {
            return json(['code' => 1, 'msg' => '选中的分类中有关联症状，无法删除']);
        }

        $result = Db::name('symptom_categories')->whereIn('id', $ids)->delete();

        if ($result) {
            return json(['code' => 0, 'msg' => '批量删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '批量删除失败']);
        }
    }

    /**
     * 更新排序
     */
    public function updateSort()
    {
        $data = input('post.');

        if (empty($data) || !is_array($data)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        Db::startTrans();
        try {
            foreach ($data as $item) {
                if (isset($item['id']) && isset($item['sort_order'])) {
                    Db::name('symptom_categories')
                        ->where('id', $item['id'])
                        ->update(['sort_order' => $item['sort_order']]);
                }
            }
            Db::commit();
            return json(['code' => 0, 'msg' => '排序更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => '排序更新失败']);
        }
    }

    /**
     * 获取所有启用的分类（用于下拉选择）
     */
    public function getActiveList()
    {
        $list = Db::name('symptom_categories')
            ->where('is_active', 1)
            ->field('id,name_zh_cn,name_en_us,name_ja_jp,name_be_by')
            ->order('sort_order asc, id asc')
            ->select();

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $list
        ]);
    }
}
